import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/config/route/sale_check_widget_route.dart';
import 'package:dk_flutter_module_sale/r.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_check_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint_list/bean/list_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint_list/bean/list_config_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint_list/widget/cell_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint_list/widget/search_bar_widget.dart';


@ARoute(url: SaleCheckWidgetRoute.SALE_CHECK_ROOM_PAINT_LIST)
//房态采集
class PageRoomPaintList extends CommonPageWithTrack {
  final BoostRouteOption option;

  PageRoomPaintList(this.option) : super();

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("巡房-房态采集-列表", null);
  }

  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    //请求配置接口
    pageBloc.dataHttpGet(
        path: SaleCheckApi.roomPaintListConfig,
        handleResult: (dynamic data) {
          Map<String,dynamic> defaultMap = Map();
          ListConfigData configData = ListConfigData.fromJson(data);
          SearchDefaultRequestBean listDefaultRequestDataBean = configData.listDefaultRequestData?.searchDefaultRequest;
          if(objNotEmpty(listDefaultRequestDataBean)) {
            defaultMap[listDefaultRequestDataBean.searchKey] = listDefaultRequestDataBean.searchValue;
          }
          ///分页
          defaultMap["pageNum"] = 1;
          defaultMap["pageSize"] = 20;
          //请求列表接口
          pageBloc.dataHttpGet(
            path: SaleCheckApi.roomPaintList,
            queryMap: defaultMap,
            handleResult: (dynamic listData) {
              ResultData resultData = ResultData.fromJson(listData);
              pageBloc.switchPage(RoomPaintStatefulWidget(configData,pageBloc, resultData));
            },
            showLoading: false,
          );
        },
        showLoading: false);
  }
}

class RoomPaintStatefulWidget extends StatefulWidget {
  final ResultData resultData;
  final CommonPageBloc pageBloc;
  final ListConfigData configData;
  RoomPaintStatefulWidget(
      this.configData,
      this.pageBloc,
      this.resultData,
      );

  @override
  _RoomPaintStatefulWidgetState createState() =>
      _RoomPaintStatefulWidgetState(this.configData, this.pageBloc,this.resultData);
}

class _RoomPaintStatefulWidgetState extends State<RoomPaintStatefulWidget> {
  static const String pageNumberKey = "pageNum";
  final CommonPageBloc pageBloc;
  Map<String,dynamic> paramsMap;
  ResultData resultData;
  int pageIndex = 1;
  DkEasyRefreshController easyRefreshController;
  ListConfigData configData;
  String searchText = "";
  _RoomPaintStatefulWidgetState(
      this.configData,
      this.pageBloc,
      this.resultData,
      );
  @override
  void initState() {
    // TODO: implement initState
    easyRefreshController = DkEasyRefreshController();
    super.initState();
    this.paramsMap = {};
    ///分页
    this.paramsMap[pageNumberKey] = 1;
    this.paramsMap["pageSize"] = 20;

    ///默认搜索
    SearchDefaultRequestBean listDefaultRequestDataBean = this.configData.listDefaultRequestData?.searchDefaultRequest;
    if(objNotEmpty(listDefaultRequestDataBean)) {
      this.searchText = listDefaultRequestDataBean.displayName;
      this.paramsMap[listDefaultRequestDataBean.searchKey] = listDefaultRequestDataBean.searchValue;
    } else if(objNotEmpty(widget.configData.searchData)) {
      this.searchText = this.configData.searchData.placeholder;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DkAppBar(
        DKAppBarParams.withBackMenu(context,buildRightNavigationItem(),
            title: Text("房态采集列表")),
      ),
      body: _commonListWidget(),
    );
  }
  
  void clearSearchCondition() {
    //清空搜索条件
    if(stringNotEmpty(this.configData.searchData.dimKey)) {
      paramsMap.remove(this.configData.searchData.dimKey);
    }
    if(listNotEmpty(this.configData.searchData.listData)) {
      for(int i = 0;i < this.configData.searchData.listData.length;i++) {
        SearchItem item = this.configData.searchData.listData[i];
        paramsMap.remove(item.searchKey);
      }
    }
  }

  //处理搜索回调
  void handleSearch(Map<String, dynamic> resultMap) {
    //清空搜索
    this.clearSearchCondition();
    SearchCallBackBean bean = SearchCallBackBean.fromJson(resultMap);
    if(stringNotEmpty(bean.searchValue)) {
      //searchBarWidgetBloc.dispatch(bean.displayName);
      this.searchText = bean.displayName;
      paramsMap[bean.searchKey] = bean.searchValue;
    } else {
      this.searchText = configData.searchData.placeholder;
    }
    setState(() {
      this.refreshList(showLoading: true);
    });
  }

  Widget _commonListWidget() {
    if(objEmpty(this.resultData)){
      return SizedBox(width: 0 ,height: 0,);
    }
    bool noMore = this.pageIndex >= this.resultData.pages;
    return  Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          DkVisibilityCompose(
              VisibilityComposeOption.gone((BuildContext context){
                return SearchBarWidget(
                  tapAction: (){
                    RouteUtil.goPage(
                        CommonWidgetRoute.COMMON_SEARCH_LIST,
                        widgetContext:this.context,
                        widgetParams: this.widget.configData.searchData.toJson(),
                        widgetResultCallback: (map){
                          if(map != null) {
                            handleSearch(map);
                          }
                        }
                    );
                  },
                  placeholder: this.searchText,
                );
              },visible: objNotEmpty(widget.configData.searchData))
          ),
          Expanded(
            child: Container(
              color: Color(0xFFF7F8FA),
              child: DkRefreshListWidget.custom(
                  controller: easyRefreshController,
                  onRefresh: refreshList,
                  onLoad: noMore ? null : loadMore,
                  emptyWidget: this.resultData.data.length == 0 ? LogicPage.emptyPage(emptyParam: SaleConfig.emptyPageParam) : null,
                  slivers: <Widget>[
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                            (BuildContext context,int index) {
                          Data item = resultData.data[index];
                          return CellWidget(
                            tapAction: (){
                              RouteUtil.goPage(item.route);
                            },
                            title:item.detail,
                            leftName: "创建时间：" + item.createTime,
                            rightName: "创建人：" + item.operator,
                          );
                        },
                        childCount: this.resultData.data.length,
                      ),
                    ),
                  ]),
            ),
          )
        ],
      ),
    );
  }

  Future<void> loadMore() async {
    paramsMap[pageNumberKey] = (++this.pageIndex);
    pageBloc.dataHttpGet(
        path: SaleCheckApi.roomPaintList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          setState(() {
            ResultData result = ResultData.fromJson(data);
            resultData.data.addAll(result.data);
            easyRefreshController.finishLoad(success: true,noMore: this.pageIndex >= result.pages);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1,dynamic data2){
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1){
          easyRefreshController.finishLoad(success: false);
        }
    );
  }

  Future<void> refreshList({showLoading = false}) {
    pageIndex = 1;
    paramsMap[pageNumberKey] = pageIndex;
    pageBloc.dataHttpGet(
        path: SaleCheckApi.roomPaintList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          setState(() {
            resultData = ResultData.fromJson(data);
            easyRefreshController.finishRefresh(success: true);
          });
        },
        showLoading: showLoading,
        handleErrorCode: (responseData){
          setState(() {
            showShortToast(responseData.msg);
            easyRefreshController.finishRefresh(success: false);
          });
        },
        handleFailResult: (dynamic data1,dynamic data2){
          easyRefreshController.finishRefresh(success: false);
        }
    );
    return new Future.value();
  }

  List<Widget> buildRightNavigationItem() {
    List<RightNavigationItem> items = this.configData.rightNavigationDataList;
    if (items.length == 0) return [];
    if (items.length == 1) {
      RightNavigationItem item = items.first;
      return [
        InkWell(
          child: Padding(
            padding: EdgeInsets.only(left: 15, right: 10),
            child: Center(
              child: item.showType == "text"
                  ? DkText.simple(
                item.textStyle.text,
                16,
                DkColor(item.textStyle.textColor),
              )
                  : Image.network(item.imageStyle.image, width: 16, height: 16,
              ),
            ),
          ),
          onTap: () {
            if (stringBlank(item.route)) {
              return;
            }
            RouteUtil.goPage(item.route);
          },
        )
      ];
    }
    return [
      DkPopupMenuButton(
        child: IconButton(
          icon: Image.asset(R.imagesCommonListItemPng),
          padding: EdgeInsets.only(right: 20),
        ),
        itemBuilder: (BuildContext context) {
          return items.map((i) {
            return PopupMenuItem(
              value: 1,
              child: GestureDetector(
                child: Center(
                  child: DkText.simple(
                    i.textStyle.text,
                    16,
                    Color(0xff333333),
                  ),
                ),
                onTap: () {
                  RouteUtil.goPage(i.route);
                },
              ),
            );
          }).toList();
        },
        offset: Offset(0, 100),
      )
    ];
  }
}

